from PySide6.QtWidgets import (
    QGroupBox, QVBoxLayout, QGridLayout, QHBoxLayout,
    QPushButton, QLabel, QCheckBox, QScrollArea, QWidget, QSizePolicy, QComboBox
)
from PySide6.QtCore import Qt

from presenter.server_presenter import ServerPresenter
from view.components.toast_widget import ToastWidget


class ServerWidget(QGroupBox):
    """
    通用服务器选择组件
    """        

    def __init__(self, title="目标服务器（可多选）", server_manager=None):
        super().__init__(title)
        self.server_pr = ServerPresenter(self, server_manager)
        self.servers = self.server_pr.handle_load_servers() # all_servers
        self.checkboxes = []

        self.init_ui()
        self.init_connections()

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(8, 8, 8, 8)
        layout.setSpacing(6)

        # 按钮行
        btn_layout = QHBoxLayout()
        self.station_combo = QComboBox()
        self.select_all_btn = QPushButton("全选")
        self.deselect_all_btn = QPushButton("全不选")
        self.station_combo.setPlaceholderText("选择工站")
        self.test_connection_btn = QPushButton("测试连接")

        btn_layout.addWidget(self.station_combo)
        btn_layout.addWidget(self.select_all_btn)
        btn_layout.addWidget(self.deselect_all_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.test_connection_btn)
        layout.addLayout(btn_layout)

        # 滚动区
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scroll_area.setFrameShape(QScrollArea.NoFrame)

        self.inner_widget = QWidget()
        self.grid_layout = QGridLayout(self.inner_widget)

        self.grid_layout.setContentsMargins(4, 4, 4, 4)
        self.grid_layout.setSpacing(4)
        self.scroll_area.setWidget(self.inner_widget)
        layout.addWidget(self.scroll_area)

        # 底部状态
        self.selected_count_label = QLabel("已选择 0 台服务器")
        layout.addWidget(self.selected_count_label)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.set_servers()


    def init_connections(self):
        """初始化信号连接"""
        self.select_all_btn.clicked.connect(self.on_select_all)
        self.deselect_all_btn.clicked.connect(self.on_deselect_all)
        self.test_connection_btn.clicked.connect(self.on_test_connection)
        self.station_combo.currentIndexChanged.connect(self.on_station_changed)
        self.server_pr.server_connect_status.connect(self.update_server_status)

    def set_servers(self):
        """设置服务器数据并初始化下拉框"""
        self.station_combo.blockSignals(True)
        self.station_combo.clear()
        self.station_combo.addItem("全部工站")
        station_names = sorted(set(s.get('station', 'Unknown') for s in self.servers))
        self.station_combo.addItems(station_names)
        self.station_combo.blockSignals(False)

        self._load_checkboxes(self.servers)

    def on_station_changed(self):
        """根据工站过滤服务器列表"""
        if not self.servers:  
            return
        
        station = self.station_combo.currentText()
        if station == "全部工站":
            filtered = self.servers
        else:
            filtered = [s for s in self.servers if s['station'] == station]
        
        self._load_checkboxes(filtered)

    def _load_checkboxes(self, servers):
        """加载复选框"""
        for i in reversed(range(self.grid_layout.count())):
            widget = self.grid_layout.itemAt(i).widget()
            if widget:
                widget.setParent(None)

        self.checkboxes.clear()

        # 动态布局
        row, col = 0, 0
        for s in servers:
            ip = s.get("ip")
            label = f"{s.get('station', 'Unknown')} ({ip})"
            cb = QCheckBox(label)
            cb.setChecked(s.get("selected", False))
            cb.setProperty('ip', ip)
            cb.setProperty('username', s.get('username'))
            cb.setProperty('password', s.get('password'))
            cb.setProperty("station", s.get("station"))

            cb.toggled.connect(lambda checked, ip=ip: self.server_pr.server_manager.toggle_server(ip, checked))   # 勾选状态刷新到服务器管理器
            cb.toggled.connect(self._update_selected_count)

            self.grid_layout.addWidget(cb, row, col)
            self.checkboxes.append(cb)

            col += 1
            if col >= 4: 
                row += 1
                col = 0
        
        row_count = (len(self.checkboxes) + 3) // 4

        total_height = 35 * row_count
        if row_count == 2:
            total_height -= 3*row_count
        elif row_count == 3:
            total_height -= 6*row_count
        self.scroll_area.setMaximumHeight(min(total_height, 250))
        self._update_selected_count()
        
    def _update_selected_count(self):
        """"勾选统计"""
        count = sum(cb.isChecked() for cb in self.checkboxes)
        self.selected_count_label.setText(f"已选择 {count} 台服务器")

    def on_select_all(self):
        """全选"""
        for cb in self.checkboxes:
            cb.setChecked(True)
        self._update_selected_count()
        self.server_pr.handle_select_all(self.servers) 

    def on_deselect_all(self):
        """全不选"""
        for cb in self.checkboxes:
            cb.setChecked(False)
        self._update_selected_count()
        self.server_pr.handle_deselect_all()
    
    def on_test_connection(self):
        """测试连接"""
        selected = self.server_pr.server_manager.get_selected_servers()
        if not selected:
            ToastWidget(self, "请选择服务器！")
            return
        self.server_pr.handle_connection(selected)

    def update_server_status(self, results):
        """更新服务器状态"""
        for cb in self.checkboxes:
            ip = cb.property("ip")
            if ip not in results:
                cb.setStyleSheet("color: black")
                continue
            
            r = results[ip]
            if r.get("status", False):
                cb.setStyleSheet("color: #2ecc71")
            else:
                cb.setStyleSheet("color: #e74c3c")
